# 第一阶段：提取词典文件
FROM golang:1.24-bookworm AS dict-extractor

# 使用中科大 Debian 源（适配 Bookworm 新结构）
RUN mkdir -p /etc/apt/sources.list.d && \
    echo "deb https://mirrors.ustc.edu.cn/debian bookworm main contrib non-free" > /etc/apt/sources.list && \
    echo "deb https://mirrors.ustc.edu.cn/debian bookworm-updates main contrib non-free" >> /etc/apt/sources.list && \
    echo "deb https://mirrors.ustc.edu.cn/debian-security bookworm-security main" >> /etc/apt/sources.list && \
    apt-get update && \
    apt-get install -y --no-install-recommends git ca-certificates && \
    rm -rf /var/lib/apt/lists/* && \
    git config --global http.sslVerify true && \
    git clone --depth 1 https://github.com/yanyiwu/cppjieba.git /cppjieba && \
    mkdir -p /dict && cp -r /cppjieba/dict/* /dict

# 第二阶段：构建应用
FROM golang:1.24-bookworm AS builder

# 配置中科大 Debian 源
RUN mkdir -p /etc/apt/sources.list.d && \
    echo "deb https://mirrors.ustc.edu.cn/debian bookworm main contrib non-free" > /etc/apt/sources.list && \
    echo "deb https://mirrors.ustc.edu.cn/debian bookworm-updates main contrib non-free" >> /etc/apt/sources.list && \
    echo "deb https://mirrors.ustc.edu.cn/debian-security bookworm-security main" >> /etc/apt/sources.list && \
    apt-get update && \
    apt-get install -y --no-install-recommends gcc && \
    rm -rf /var/lib/apt/lists/*

# 配置Go环境
WORKDIR /app
ENV GOPROXY=https://goproxy.cn,direct \
    CGO_ENABLED=1 \
    GOOS=linux \
    GOARCH=amd64

# 复制词典文件
COPY --from=dict-extractor /dict /app/dict

# 复制依赖文件
COPY go.mod go.sum ./
RUN go mod download -x

# 复制源码并构建
COPY . .
RUN go build -v -ldflags="-w -s" -o /app/blogcenter .

# 第三阶段：运行环境
FROM ubuntu:22.04

# 使用中科大 Ubuntu 源
RUN sed -i 's/archive.ubuntu.com/mirrors.ustc.edu.cn/g' /etc/apt/sources.list && \
    sed -i 's/security.ubuntu.com/mirrors.ustc.edu.cn/g' /etc/apt/sources.list && \
    apt-get update && \
    apt-get install -y --no-install-recommends \
        ca-certificates \
        tzdata && \
    ln -fs /usr/share/zoneinfo/Asia/Shanghai /etc/localtime && \
    echo "Asia/Shanghai" > /etc/timezone && \
    rm -rf /var/lib/apt/lists/*

# 部署应用
WORKDIR /app
COPY --from=builder /app/blogcenter .
COPY --from=builder /app/dict /app/dict
COPY etc /app/etc

# 设置权限
RUN chmod +x /app/blogcenter && \
    chmod -R 755 /app/dict

EXPOSE 8889
CMD ["./blogcenter", "-f", "etc/blogcenter-api.yaml"]